// 导入
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || null,
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  stToken(state, token) {
    // 存储都仓库
    state.token = token
    // 存储到本地local/cookie
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
  }
}

const actions = {
  async login(context, data) {
    // 1.发送请求
    // 2.拿token - 进行存储
    const token = await login(data)
    console.log(token)
    // 3. 提交mutations token  123456
    context.commit('stToken', token)
  },

  async getUserInfo(context) {
    const data = await getUserInfo()
    console.log(data)
    context.commit('setUserInfo', data)
    return data
  },

  // 退出登录的action
  logout(context) {
    context.commit('removeToken') // 删除token
    context.commit('setUserInfo', {}) // 设置用户信息为空对象
    // 重置路由
    resetRouter()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
